const Message = require('../../models/Message');
const User = require('../../models/User');
const {Op} = require('sequelize');
const dayjs = require('dayjs');

const MessageAddMiddleWare = (req,res)=>{
    let {uid,hid,content} = req.body;
    let time = new Date();
    Message.create({content,hourse_id:hid,user_id:uid,create_time:dayjs(time).format('YYYY-MM-DD HH:mm:ss')}).then(val=>{
        console.log("val ",val);
    }).catch(err=>{
        console.log("err ",err);
    });
    res.send('success');
}

const GetMesssageByUserIdMiddleWare = (req,res)=>{
    let {id} = req.params;
    Message.findAll({
        where:{
            user_id:id
        }
    }).then(val=>{
        return val.map(v=>{
            v.dataValues.create_time = dayjs(v.dataValues.create_time).format('YYYY-MM-DD HH:mm:ss');
            return v.dataValues;
        });
    }).then(value=>{
        res.send(value);
    })
}

const GetMessageByMessageIdMiddleWare = (req,res)=>{
    let {id} = req.body;
    Message.findOne({
        where:{
            id
        }
    }).then(val=>{
        res.send(val.dataValues);
    })
}

const EditMessageByMessageIdMiddleWare = (req,res)=>{
    let {mid,uid,content,hid} = req.body;
    Message.update({content,hourse_id:hid,user_id:uid,create_time:dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')},{where:{id:mid}});
    res.send('success');
}

const DeleteMessageByMessageIdMiddleWare = (req,res)=>{
    let {id} = req.params;
    Message.destroy({
        where:{
            id
        }
    });
    res.send('success');
}

const showAllMessageMiddleWare = (req,res)=>{
    Message.findAll().then(val=>val.map(v=>v.dataValues)).then(v=>{
        let result = v.map(obj=>{
            obj.create_time = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
            return obj;
        })
       res.send(result);
    });

}
module.exports = {
    MessageAddMiddleWare,
    GetMesssageByUserIdMiddleWare,
    GetMessageByMessageIdMiddleWare,
    EditMessageByMessageIdMiddleWare,
    DeleteMessageByMessageIdMiddleWare,
    showAllMessageMiddleWare
}